package com.atguigu.guli.edu.excel;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.atguigu.guli.edu.dao.EduSubjectDao;
import com.atguigu.guli.edu.entity.Subject;
import com.atguigu.guli.edu.entity.excel.SubjectDate;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

public class ExcelImportListener extends AnalysisEventListener<SubjectDate> {
    private EduSubjectDao subjectDao;


    public ExcelImportListener(EduSubjectDao subjectDao) {
        this.subjectDao = subjectDao;
    }


    @Override
    public void invoke(SubjectDate subjectDate, AnalysisContext analysisContext) {
        //获取一级名称
        String levelOneSubjectTitle = subjectDate.getLevelOneSubjectTitle();
        //二级分类名称
        String levelTwoSubjectTitle = subjectDate.getLevelTwoSubjectTitle();

        //添加一级分类
        LambdaQueryWrapper<Subject> queryWrapper = new LambdaQueryWrapper<Subject>();
        queryWrapper.eq(Subject::getParentId, "0");
        queryWrapper.eq(Subject::getTitle,levelOneSubjectTitle);
        Subject subject = subjectDao.selectOne(queryWrapper);
        //如果为空 则数据库没有该分类
        if (subject==null){
            subject = new Subject();
            subject.setParentId("0");
            subject.setTitle(levelOneSubjectTitle);
            subject.setSort(0);
            subjectDao.insert(subject);
        }

        //添加二级分类
         //1.清空查询条件
         queryWrapper.clear();
         //2.查询该分类名称和父分了id
        queryWrapper.eq(Subject::getTitle,levelTwoSubjectTitle);
        queryWrapper.eq(Subject::getParentId,subject.getId());
        Integer integer = subjectDao.selectCount(queryWrapper);
        if (integer==0){
            Subject subject1 = new Subject();
            subject1.setTitle(levelTwoSubjectTitle);
            subject1.setSort(0);
            subject1.setParentId(subject.getId());
            subjectDao.insert(subject1);
        }

    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}
